/**============================================================================
 *
 * Author: luo1o1o1o 
 *
 * QQ: 330240995, PHONE: 17600071321
 *
 * Last modified: 2021-06-23 14:12
 *
 * Filename: utils.js
 *
 * Description: urils controller
 *
 ============================================================================**/
const path = require('path')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { uploadFileSizeFailInfo } = require('../model/ErrorInfo')
const fse = require('fs-extra')

// 存储目录
const DIST_FOLDER_PATH = path.join(__dirname, '..', '..', 'uploadFiles')

// 文件最大体积1M
const MIX_SIZE = 1024 * 1024 * 1024

fse.pathExists(DIST_FOLDER_PATH).then((exist) => {
    if (!exist) {
        fse.ensureDir(DIST_FOLDER_PATH)
    }
})

/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-24 10:21
 * @desc: 保存文件
 * @param: {string} name 文件名
 * @param: {string} type 文件类型
 * @param: {number} size 文件体积大小
 * @param: {string} filePath 文件路径
 */
async function saveFile({ name, type, size, filePath }) {
    // 如果文件体积过大，删除
    if (size > MIX_SIZE) {
        await fse.remove(filePath)
        return new ErrorModel()
    }
    // 移动文件
    const fileName = Date.now() + '.' + name // 防止重名
    const distFilePath = path.join(DIST_FOLDER_PATH, fileName) // 目的地
    await fse.move(filePath, distFilePath)

    // 返回信息
    return new SuccessModel({
        url: '/' + fileName,
    })
}

module.exports = {
    saveFile,
}
